<?php
declare (strict_types=1);

namespace app\beautiful\controller\cashier;

use app\BaseController;
use app\beautiful\logic\LogsLogic;
use app\beautiful\logic\MemberWalletLogic;
use app\beautiful\logic\order\OrderLogic;
use app\beautiful\logic\PartnerLogic;
use app\beautiful\logic\printer\PrinterLogic;
use app\beautiful\model\CouponModel;
use app\beautiful\model\logs\ApplyLogsModel;
use app\beautiful\model\logs\MemberBalanceLogsModel;
use app\beautiful\model\logs\MemberCouponLogsModel;
use app\beautiful\model\logs\MemberIntegralLogsModel;
use app\beautiful\model\logs\ProjectWriteOffModel;
use app\beautiful\model\member\MemberBalanceModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\member\MemberIntegralModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\member\MemberOnceCardItemModel;
use app\beautiful\model\member\MemberOnceCardModel;
use app\beautiful\model\member\MemberProjectModel;
use app\beautiful\model\member\MemberSnapUpModel;
use app\beautiful\model\order\BuyOrderModel;
use app\beautiful\model\order\CashierOrderModel;
use app\beautiful\model\order\GoodsOrderModel;
use app\beautiful\model\project\OnceCardModel;
use app\beautiful\model\setting\SettingBalanceModel;
use app\beautiful\model\setting\SettingSmsModel;
use app\common\logic\DataLogic;
use app\common\logic\SmsLogic;
use think\facade\Db;

class Member extends BaseController
{
    protected $name = '会员';

    public function showMember()
    {
        $member_id = $this->request->param('member_id/d', 0);
        if (null === $member = MemberModel::find($member_id)) return $this->error($this->name . '不存在');
        if ($member->is_delete != 0) return $this->error($this->name . '不存在');
        if ($member->shop_id != $this->request->shopId) return $this->error($this->name . '不存在');

        $balance = MemberBalanceModel::where([
                ['shop_id', '=', $this->request->shopId],
                ['member_id', '=', $member_id],
                ['valid_bg_time', '<=', $this->request->time()]
            ])->sum('remain_balance') ?? 0;

        $integral = MemberIntegralModel::where([
                ['shop_id', '=', $this->request->shopId],
                ['member_id', '=', $member_id],
                ['expire_time', '>', $this->request->time()]
            ])->sum('remain_integral') ?? 0;

        $detail = [
            'balance' => $balance,
            'integral' => $integral,
        ];
        return $this->success(['detail' => $detail]);
    }

    public function saveMember()
    {
        $mobile = $this->request->param('mobile');
        $nick_name = $this->request->param('nick_name');
        if (empty($mobile)) return $this->error('请填写手机号码');
        if (!is_mobile($mobile)) return $this->error('请填写正确的手机号');
        if (empty($nick_name)) return $this->error('请填写会员名');
        $member = new MemberModel();
        $member->shop_id = $this->request->shopId;
        $where = [
            ['shop_id', '=', $this->request->shopId],
            ['mobile', '=', $mobile]
        ];
        if (null !== MemberModel::where($where)->find()) {
            return $this->error('手机号已存在');
        }
        $member->mobile = $mobile;
        $member->nick_name = $nick_name;
        $member->save();
        return $this->success(['member_id' => $member->member_id]);
    }

    public function getMemberDetail()
    {
        $member_id = $this->request->param('member_id/d', 0);
        if (null === $member = MemberModel::find($member_id)) {
            return $this->error($this->name . '不存在');
        }
        if ($member->is_delete != 0) {
            return $this->error($this->name . '不存在');
        }
        if ($member->shop_id != $this->request->shopId) {
            return $this->error($this->name . '不存在');
        }
        $member->append(['birthday']);

        $once_card_num = MemberOnceCardModel::where([
                ['shop_id', '=', $this->request->shopId],
                ['member_id', '=', $member_id],
                ['status', '=', 1],
            ])->count() ?? 0;

        $snaup_up_num = MemberSnapUpModel::where([
                ['shop_id', '=', $this->request->shopId],
                ['member_id', '=', $member_id]
            ])->count() ?? 0;

        $balance = MemberBalanceModel::where([
                ['shop_id', '=', $this->request->shopId],
                ['member_id', '=', $member_id],
            ])->sum('remain_balance') ?? 0;

        $use_balance = MemberBalanceModel::where([
                ['shop_id', '=', $this->request->shopId],
                ['member_id', '=', $member_id],
                ['valid_bg_time', '<=', $this->request->time()]
            ])->sum('remain_balance') ?? 0;

        $frozen_balance = MemberBalanceModel::where([
                ['shop_id', '=', $this->request->shopId],
                ['member_id', '=', $member_id],
                ['valid_bg_time', '>', $this->request->time()]
            ])->sum('remain_balance') ?? 0;

        $integral = MemberIntegralModel::where([
                ['shop_id', '=', $this->request->shopId],
                ['member_id', '=', $member_id],
                ['expire_time', '>', $this->request->time()]
            ])->sum('remain_integral') ?? 0;

        $coupon_count = MemberCouponModel::where([
                ['shop_id', '=', $this->request->shopId],
                ['member_id', '=', $member_id],
                ['status', '=', 0],
            ])->count() ?? 0;

        $detail = [
            'nick_name' => $member->nick_name,
            'level_name' => $member->level ? $member->level->name : '普通会员',
            'mobile' => $member->mobile,
            'face' => $member->face,
            'rank_num' => $member->rank_num,
//            'adviser'=>$member->adviser ? $member->adviser->staff->name : '暂无',
//            'staff_id'=>$member->adviser ? $member->adviser->staff->staff_id : 0,
            'once_card_num' => $once_card_num,
            'balance' => $balance,
            'use_balance' => $use_balance,
            'frozen_balance' => $frozen_balance,
            'integral' => $integral,
            'coupon_count' => $coupon_count,
            'snaup_up_num' => $snaup_up_num,
        ];
        return $this->success(['detail' => $detail]);
    }

    public function balanceRecharge()
    {
        $member_id = $this->request->param('member_id/d', 0);
        if (null === $member = MemberModel::find($member_id)) return $this->error($this->name . '不存在');
        if ($member->is_delete != 0) return $this->error($this->name . '不存在');
        if ($member->shop_id != $this->request->shopId) return $this->error($this->name . '不存在');

        $balance = $this->request->param('balance/f', 0);
        $give_balance = $this->request->param('give_balance/f', 0);
        if ($balance <= 0) return $this->error('请填写充值金额，且金额不能小于等于0');
        if ($give_balance < 0) return $this->error('请填写赠送金额，金额不能小于0');

        $balance_setting = SettingBalanceModel::where([['shop_id', '=', $this->request->shopId]])->find();
        $frozen_days = $balance_setting->is_frozen_give_money == 1 ? $balance_setting->frozen_days : 0;

        Db::startTrans();
        try {
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);
            $res = $MemberWalletLogic->addBalance($balance, $give_balance, 20, '', $this->request->staffId);
            if ($res == false) {
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            Db::commit();
            return $this->success('操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function balanceDeduction()
    {
        $member_id = $this->request->param('member_id/d', 0);
        if (null === $member = MemberModel::find($member_id)) return $this->error($this->name . '不存在');
        if ($member->is_delete != 0) return $this->error($this->name . '不存在');
        if ($member->shop_id != $this->request->shopId) return $this->error($this->name . '不存在');

        $balance = $this->request->param('balance/f', 0);
        $original_deduction = $this->request->param('original_deduction/f', 0);
        if ($balance <= 0) return $this->error('请填写扣除金额，且金额不能小于等于0');
        if ($original_deduction <= 0) return $this->error('请填写原本扣除金额，金额不能小于等于0');
        if ($original_deduction < $balance) return $this->error('原本扣除的金额不能小于实际扣除的金额');

        $remarks = $this->request->param('remarks');

        Db::startTrans();
        try {
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);
            $res = $MemberWalletLogic->useBalance($balance, $original_deduction, 21, $remarks, $this->request->staffId);
            if ($res == false) {
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            Db::commit();
            return $this->success('操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }

    }

    public function integralRecharge()
    {
        $member_id = $this->request->param('member_id/d', 0);
        if (null === $member = MemberModel::find($member_id)) return $this->error($this->name . '不存在');
        if ($member->is_delete != 0) return $this->error($this->name . '不存在');
        if ($member->shop_id != $this->request->shopId) return $this->error($this->name . '不存在');

        $integral = $this->request->param('integral/d', 0);
        if ($integral <= 0) return $this->error('请填写充值积分，且积分不能小于等于0');


        Db::startTrans();
        try {
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);
            $res = $MemberWalletLogic->addIntegal($integral, 20, '', $this->request->staffId);
            if (!$res) {
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            Db::commit();
            return $this->success('操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function integralDeduction()
    {
        $member_id = $this->request->param('member_id/d', 0);
        if (null === $member = MemberModel::find($member_id)) return $this->error($this->name . '不存在');
        if ($member->is_delete != 0) return $this->error($this->name . '不存在');
        if ($member->shop_id != $this->request->shopId) return $this->error($this->name . '不存在');

        $integral = $this->request->param('integral/d', 0);
        if ($integral <= 0) return $this->error('请填写积分，且积分不能小于等于0');

        $remarks = $this->request->param('remarks');


        Db::startTrans();
        try {
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);
            $res = $MemberWalletLogic->useIntegral($integral, 21, $remarks, $this->request->staffId);
            if (!$res) {
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            Db::commit();
            return $this->success('操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    /****************************************************** --end--会员详情--end--*********************************************************************/


    /****************************************************** --start--会员详情优惠券--start--*********************************************************************/


    public function getMemberCouponList()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $status = $this->request->param('status');
        $money_limit = $this->request->param('money_limit/f',0);
        $valid = $this->request->param('valid/d',0);
        $project_type_id = $this->request->param('project_type_id');
        $exclude = $this->request->param('exclude/a',[]);
        $where = [
            ['mc.shop_id', '=', $this->request->shopId]
        ];
        if ($project_type_id != null) {
            $where[] = ['coupon.project_type_id', '=', $project_type_id];
        }
        if (!empty($member_id)) $where[] = ['mc.member_id', '=', $member_id];
        if (!empty($money_limit)) $where[] = ['mc.money_limit', '<=', $money_limit];
        if (!empty($valid) && $valid==1 ) {
            $currentDate = date("Y-m-d");
            $where[] = ['mc.valid_bg_time', '<=', $currentDate];
            $where[] = ['mc.valid_end_time', '>=', $currentDate];
        }
        if (!empty($exclude)){
            $where[] = ['mc.member_coupon_id', 'not in', $exclude];
        }

        if ($status!='' && $status!=null) $where[] = ['mc.status', '=', $status];

        $order = ['add_time' => 'desc'];

        $db = Db::table('wyu_beautiful_member_coupon mc')
            ->leftJoin('wyu_beautiful_coupon coupon', 'mc.coupon_id = coupon.coupon_id')
            ->where($where);
        $total = $db->count();

        $list = Db::table('wyu_beautiful_member_coupon mc')
            ->field('mc.*,pt.name project_type_name,pt.project_type_id')
            ->leftJoin('wyu_beautiful_coupon coupon', 'mc.coupon_id = coupon.coupon_id')
            ->leftJoin('wyu_beautiful_project_type pt', 'coupon.project_type_id = pt.project_type_id')
            ->where($where)
            ->order($order)
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->select();

        return $this->success(['total' => $total, 'list' => $list]);
    }

    public function getMemberCouponListPro()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $project_type_id = $this->request->param('project_type_id');
        $where = [
            ['mc.shop_id', '=', $this->request->shopId]
        ];
        if (!empty($member_id)) $where[] = ['mc.member_id', '=', $member_id];
        if ($project_type_id != null) {
            $where[] = ['coupon.project_type_id', '=', $project_type_id];
        }
        $order = ['mc.add_time' => 'desc'];
        $field = "mc.*,coupon.project_type_id";
        $db = Db::table('wyu_beautiful_member_coupon mc')
            ->leftJoin('wyu_beautiful_coupon coupon', 'mc.coupon_id = coupon.coupon_id')
            ->where($where);
        $total = $db->count();
        $list = Db::table('wyu_beautiful_member_coupon mc')
            ->leftJoin('wyu_beautiful_coupon coupon', 'mc.coupon_id = coupon.coupon_id')
            ->where($where)
            ->field($field)
            ->order($order)
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->select();

        return $this->success(['total' => $total, 'list' => $list]);
    }

    public function getMemberCouponLogsList()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $nick_name = $this->request->param('nick_name');
        $mobile = $this->request->param('mobile');
        $type = $this->request->param('type/d');
        $where = [
            ['shop_id', '=', $this->request->shopId]
        ];

        //会员判断
        $member_where = [
            ['shop_id', '=', $this->request->shopId],
            ['is_delete', '=', 0]
        ];
        if (!empty($member_id)) $member_where[] = ['member_id', '=', $member_id];
        if (!empty($nick_name)) $member_where[] = ['nick_name', '=', $nick_name];
        if (!empty($mobile)) $member_where[] = ['mobile', '=', $mobile];
        $member_ids = MemberModel::where($member_where)->column('member_id') ?? [];
        $where[] = ['member_id', 'in', $member_ids];

        //优惠券判断
        if (!empty($type) && in_array($type, [1, -1])) $where[] = ['type', '=', $type];

        $member_coupon_logs = new MemberCouponLogsModel();
        $member_coupon_logs = $member_coupon_logs->with(['membercoupon' => function ($query) {
            $query->field('member_coupon_id,name,coupon_money,status');
        }, 'member']);
        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format'];
        $return = DataLogic::getDataList($member_coupon_logs, $where, $order, $field, $this->request->limit, $this->request->page, $append);
        return $this->success($return);
    }

    public function chooseCoupon()
    {
        $type = $this->request->param('type');
        $keyword = $this->request->param('keyword');
        $today = date("Y-m-d", $this->request->time());
        $where = [
            ['shop_id', '=', $this->request->shopId],
            ['is_delete', '=', 0],
            ['status', '=', 1],
            ['end_time', '>=', $today]
        ];
        if ($type == 'setting_balance') $where[] = ['type_id', 'in', [1, 3]];

        if (!empty($keyword)) $where[] = ['name', 'like', '%' . $keyword . '%'];

        $coupon = new CouponModel();
        $order = ['update_time' => 'desc', 'add_time' => 'desc'];
        $field = "coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit,add_time";
        $append = ['add_time_format'];
        $return = DataLogic::getDataList($coupon, $where, $order, $field, $this->request->limit, $this->request->page, $append);
        return $this->success($return);
    }

    public function sendCoupon()
    {
        $member_id = $this->request->param('member_id/d', 0);
        if (null === $member = MemberModel::find($member_id)) return $this->error($this->name . '不存在');
        if ($member->is_delete != 0) return $this->error($this->name . '不存在');
        if ($member->shop_id != $this->request->shopId) return $this->error($this->name . '不存在');

        $coupon_ids = $this->request->param('coupon_ids/a', []);
        if (empty($coupon_ids)) return $this->error('请选择优惠券');
        $coupon_data = CouponModel::where([
            ['coupon_id', 'in', $coupon_ids],
            ['shop_id', '=', $this->request->shopId],
            ['is_delete', '=', 0],
            ['status', '=', 1],
            ['end_time', '>=', date("Y-m-d", $this->request->time())]
        ])->field('coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit,add_time')
            ->select()->toArray();
        if (empty($coupon_data)) return $this->error('请选择优惠券');


        foreach ($coupon_data as $k => $coupon) {
            $member_coupon_model = new MemberCouponModel();
            $member_coupon_data = [
                'shop_id' => $this->request->shopId,
                'member_id' => $member_id,
                'type_id' => 2,
                'coupon_id' => $coupon['coupon_id'],
                'name' => $coupon['name'],
                'coupon_money' => $coupon['coupon_money'],
                'money_limit' => $coupon['money_limit'],
                'valid_bg_time' => $coupon['valid_bg_time'],
                'valid_end_time' => $coupon['valid_end_time'],
            ];
            $member_coupon_model->save($member_coupon_data);

            LogsLogic::coupon($this->request->shopId, $member_id, 1, 20, $member_coupon_model->member_coupon_id, '', $this->request->staffId);
        }

        return $this->success('送券成功');
    }

    public function writeOffCoupon()
    {
        $member_id = $this->request->param('member_id/d', 0);
        if (null === $member = MemberModel::find($member_id)) return $this->error($this->name . '不存在');
        if ($member->is_delete != 0) return $this->error($this->name . '不存在');
        if ($member->shop_id != $this->request->shopId) return $this->error($this->name . '不存在');

        $member_coupon_id = $this->request->param('member_coupon_id/d', 0);
        if (null === $memberCoupon = MemberCouponModel::find($member_coupon_id)) return $this->error('优惠券不存在');
        if ($memberCoupon->shop_id != $this->request->shopId) return $this->error('优惠券不存在');
        if ($memberCoupon->member_id != $member_id) return $this->error('优惠券不存在');
        if ($memberCoupon->status != 0) return $this->error('该优惠券已使用过了');
        if ($memberCoupon->valid_end_time < date("Y-m-d")) return $this->error('该优惠券已过期');

        $memberCoupon->status = 1;
        $memberCoupon->save();

        LogsLogic::coupon($this->request->shopId, $member_id, -1, 21, $member_coupon_id, '', $this->request->staffId);
        return $this->success('核销成功');
    }

    /****************************************************** --end--会员详情优惠券--end--*********************************************************************/


    /****************************************************** --start--会员详情次卡--start--*********************************************************************/

    public function chooseOnceCard()
    {
        $name = $this->request->param('name');
        $member_id = $this->request->param('member_id/d', 0);
        $where = [
            ['shop_id', '=', $this->request->shopId],
            ['is_delete', '=', 0],
            ['status', '=', 1]
        ];
        if (!empty($name)) $where[] = ['name', '=', $name];


        $once_card_model = new OnceCardModel();
        $order = ['sort' => 'desc', 'add_time' => 'desc'];
        $field = '*';
        $append = ['add_time_format', 'is_flash_sale_expire', 'flash_sale_djs', 'valid_time_format'];
        $return = DataLogic::getDataList($once_card_model, $where, $order, $field, $this->request->limit, $this->request->page, $append);
        if ($this->request->page == 1) {
            $member = MemberModel::find($member_id);
            $return['member'] = [
                'level_id' => $member === null ? 0 : $member->level_id,
                'member_id' => $member === null ? 0 : $member->member_id,
            ];
        }
        return $this->success($return);
    }

    public function applyOnceCard()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $once_card_id = $this->request->param('once_card_id/d', 0);
        $total_price = $this->request->param('total_price/f', 0);
        $need_pay = $this->request->param('price/f', 0);


        //判断传来的参数
        if ($member_id == 0) return $this->error('会员不存在');
        if ($once_card_id == 0) return $this->error('次卡不存在');
        if (empty($total_price) || $total_price <= 0) return $this->error('参数错误');
        if (empty($need_pay) || $need_pay <= 0) return $this->error('请输入实际价格，且不能小于0');

        $params = [
            'member_id' => $member_id,
            'total_price' => $total_price,
            'once_card_id' => $once_card_id,
            'need_pay' => $need_pay,
            'operate_type' => 1,
            'operate_id' => $this->request->staffId,
        ];

        Db::startTrans();
        try {
            $order_logic = OrderLogic::init($this->request->shopId);
            $order_logic['once_card']->apply($params);

            //记录推广员业绩
            $PartnerLogic = new PartnerLogic($this->request->shopId);
            $PartnerLogic->commission($member_id, $need_pay);
            Db::commit();
            return $this->success('办理成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function getMemberOnceCardList()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $where = [
            ['shop_id', '=', $this->request->shopId],
            ['member_id', '=', $member_id]
        ];
        $member_once_card_model = new MemberOnceCardModel();
        $member_once_card_model = $member_once_card_model->with(['items']);
        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format', 'status_means', 'pay_type_mean', 'pay_time_format', 'status_another'];
        $return = DataLogic::getDataList($member_once_card_model, $where, $order, $field, $this->request->limit, $this->request->page, $append);
        return $this->success($return);
    }

    public function getMemberOnceCardListItem()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $project_id = $this->request->param('project_id/d', 0);
        $where = [
            ['shop_id', '=', $this->request->shopId],
            ['member_id', '=', $member_id],
            ['remain_num', '>', 0]
        ];
        if(!empty($project_id)) $where[] = ['project_id','=',$project_id];

        $member_once_card_model = new MemberOnceCardItemModel();
        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format'];
        $return = DataLogic::getDataList($member_once_card_model, $where, $order, $field, $this->request->limit, $this->request->page, $append);
        return $this->success($return);
    }

    public function writeOffOncecardOrder()
    {
        $today = date("Y-m-d", $this->request->time());
        $member_once_card_item_id = $this->request->param('member_once_card_item_id/d', 0);
        $num = $this->request->param('num/d', 0);
        $remark = $this->request->param('remark');

        if ($num <= 0) return $this->error('核销次数不能小于0');

        if ($member_once_card_item_id == 0) return $this->error($this->name . '不存在');
        if (null === $member_once_card_item = MemberOnceCardItemModel::find($member_once_card_item_id)) return $this->error($this->name . '不存在');
        if ($member_once_card_item->shop_id != $this->request->shopId) return $this->error($this->name . '不存在');

        if (null === $member_once_card = MemberOnceCardModel::find($member_once_card_item->member_once_card_id)) return $this->error($this->name . '不存在');
        if ($member_once_card->status != 1) return $this->error($this->name . '的状态不在待消费');
        if ($member_once_card->valid_end_time < $today) return $this->error($this->name . '已过期');

        if (null === $member_project = MemberProjectModel::where([
                ['member_id', '=', $member_once_card_item->member_id],
                ['source', '=', 'once_card'],
                ['project_id', '=', $member_once_card_item->project_id],
                ['member_once_card_item_id', '=', $member_once_card_item_id],
                ['total_num', '=', $member_once_card_item->total_num],
                ['remain_num', '=', $member_once_card_item->remain_num]
            ])->find()) {
            return $this->error($this->name . '不存在');
        }

        if (null === $member = MemberModel::find($member_once_card->member_id)) return $this->error($this->name . '不存在');
        if ($member->shop_id != $this->request->shopId) return $this->error($this->name . '不存在');

        $remain_num = $member_once_card_item->remain_num - $num;
        if ($remain_num < 0) return $this->error($this->name . '的剩余数量不够这次核销');
        Db::startTrans();
        try {
            //处理我的次卡项目
            $member_once_card_item->remain_num = $remain_num;
            $member_once_card_item->save();

            //处理次卡状态
            if (null === MemberOnceCardItemModel::where([
                    ['shop_id', '=', $this->request->shopId],
                    ['member_id', '=', $member->member_id],
                    ['member_once_card_id', '=', $member_once_card->member_once_card_id],
                    ['remain_num', '>', 0]
                ])->find()) {
                $member_once_card->status = 8;
                $member_once_card->save();
            }
            //处理我的项目
            $member_project->remain_num = $remain_num;
            $member_project->save();

            //添加核销记录
            $res = LogsLogic::project($this->request->shopId, $member->member_id, 'once_card', $member_once_card_item_id, $num, $remain_num, $remark, 1, $this->request->staffId);
            if (!$res) {
                Db::rollback();
                return $this->error('核销失败');
            }

            //打印机
            $printer_logic = new PrinterLogic($this->request->shopId);
            $printer_logic->print('onceCardOrderWriteOff', $res);
            Db::commit();
            return $this->success('核销成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }


    public function getMemberOnceCardLogs()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $type = $this->request->param('type/d', 1);
        if (!in_array($type, [1, 2])) $type = 1;
        switch ($type) {
            case 1:
                $return = $this->getWriteOffLogs($member_id);
                break;
            case 2:
                $return = $this->getApplyLogs($member_id);
                break;
        }

        return $this->success($return);
    }


    protected function getWriteOffLogs($member_id)
    {
        $where = [
            ['shop_id', '=', $this->request->shopId],
            ['member_id', '=', $member_id],
            ['source', '=', 'once_card'],
        ];
        $project_write_off_model = new ProjectWriteOffModel();
        $project_write_off_model = $project_write_off_model->with(['once_card' => function ($query) {
            $query->field('member_once_card_id,name');
        }]);
        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format'];
        $return = DataLogic::getDataList($project_write_off_model, $where, $order, $field, $this->request->limit, $this->request->page, $append);
        return $return;
    }

    protected function getApplyLogs($member_id)
    {
        $where = [
            ['shop_id', '=', $this->request->shopId],
            ['member_id', '=', $member_id],
            ['source', '=', 'once_card'],
        ];
        $apply_logs_model = new ApplyLogsModel();
        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format'];
        $return = DataLogic::getDataList($apply_logs_model, $where, $order, $field, $this->request->limit, $this->request->page, $append);
        return $return;
    }

    /****************************************************** --end--会员详情次卡--end--*********************************************************************/


    /****************************************************** --start--会员详情商城订单--start--*********************************************************************/

    public function getGoodsOrderList()
    {
        $status = $this->request->param('status/d', 0);
        $member_id = $this->request->param('member_id/d', 0);

        $where = [
            ['shop_id', '=', $this->request->shopId],
            ['member_id', '=', $member_id],
            ['is_delete', '=', 0],
        ];

        if (!empty($status)) $where[] = ['status', '=', $status];

        $order_model = new GoodsOrderModel();
        $order_model = $order_model->with(['skus']);

        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format', 'pay_time_format', 'status_means', 'order_type_means', 'pay_type_mean'];

        $return = DataLogic::getDataList($order_model, $where, $order, $field, $this->request->limit, $this->request->page, $append);

        return $this->success($return);
    }

    public function overGoodsOrder()
    {
        $order_id = $this->request->param('order_id/d', 0);
        if ($order_id == 0) return $this->error('订单不存在#1');
        if (null === $order = GoodsOrderModel::find($order_id)) return $this->error('订单不存在#2');
        if ($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');
        if ($order->is_delete != 0) return $this->error('订单不存在#4');
        if ($order->logistics_type != 1) $this->error('该订单无法完成');
        if ($order->status != 3) return $this->error('该订单无法完成');
        $order->status = 8;
        $order->save();
        return $this->success('订单已完成');
    }

    public function deliverGoodsOrder()
    {
        $order_id = $this->request->param('order_id/d', 0);
        if ($order_id == 0) return $this->error('订单不存在#1');
        if (null === $order = GoodsOrderModel::find($order_id)) return $this->error('订单不存在#2');
        if ($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');
        if ($order->is_delete != 0) return $this->error('订单不存在#4');
        if ($order->logistics_type != 1) $this->error('该订单无法发货');
        if ($order->status != 2) return $this->error('该订单无法发货');

        if (null === $member = MemberModel::find($order->member_id)) return $this->error('订单不存在#5');

        $order->status = 3;
        $order->save();

        //其他要补充的
        //发送短信给用户
        try {
            $sms_setting = SettingSmsModel::where([['shop_id', '=', $this->request->shopId]])->find();
            if (null !== $sms_setting) {

                if ($sms_setting->order_deliver_notice_member == 1) {
                    $sms_logic = new SmsLogic();
                    $params = [
                        'id' => (string)$order_id,
                    ];
                    $sms_logic->send($this->request->shopId, [$member->mobile], $params, 'orderDeliverNoticeMember');
                }
            }
        } catch (\Exception $e) {

        }

        return $this->success('发货成功');
    }

    public function writeOffOrder()
    {
        $order_id = $this->request->param('order_id/d', 0);
        if ($order_id == 0) return $this->error('订单不存在#1');
        if (null === $order = GoodsOrderModel::find($order_id)) return $this->error('订单不存在#2');
        if ($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');
        if ($order->is_delete != 0) return $this->error('订单不存在#4');
        if ($order->logistics_type != 2) $this->error('该订单无法核销');
        if ($order->status != 4) return $this->error('该订单无法核销');

        if (null === $member = MemberModel::find($order->member_id)) return $this->error('订单不存在#5');

        $order->status = 8;
        $order->save();

        //其他要补充的
        //发送短信给用户
        try {
            $sms_setting = SettingSmsModel::where([['shop_id', '=', $this->request->shopId]])->find();
            if (null !== $sms_setting) {

                if ($sms_setting->order_write_off_notice_member == 1) {
                    $sms_logic = new SmsLogic();
                    $params = [
                        'id' => (string)$order_id,
                    ];
                    $sms_logic->send($this->request->shopId, [$member->mobile], $params, 'orderWriteOffNoticeMember');
                }
            }
        } catch (\Exception $e) {

        }

        //打印机
        $printer_logic = new PrinterLogic($this->request->shopId);
        $printer_logic->print('orderWriteOff', $order->order_id);

        return $this->success('核销成功');
    }

    /****************************************************** --end--会员详情商城订单--end--*********************************************************************/


    /****************************************************** --start--会员详情收银订单--start--*********************************************************************/

    public function getMemberOrderList()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $where = [
            ['shop_id', '=', $this->request->shopId],
            ['is_delete', '=', 0],
            ['member_id', '=', $member_id]
        ];


        $order_model = new CashierOrderModel();
        $order_model = $order_model->with(['skus']);

        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format', 'pay_time_format', 'status_means', 'pay_type_mean'];

        $return = DataLogic::getDataList($order_model, $where, $order, $field, $this->request->limit, $this->request->page, $append);

        return $this->success($return);
    }

    /****************************************************** --end--会员详情收银订单--end--*********************************************************************/


    /****************************************************** --start--会员详情抢购--start--*********************************************************************/

    public function getMemberSnapUpList()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $project_id = $this->request->param('project_id/d', 0);
        $where = [
            ['ms.shop_id', '=', $this->request->shopId],
            ['ms.member_id', '=', $member_id]
        ];
        $order = ['add_time' => 'desc'];
        if(!empty($project_id)) $where[] = ['ms.project_id','=',$project_id];
        $db = Db::table('wyu_beautiful_member_snap_up ms')
            ->where($where);
        $total = $db->count();
        $list = Db::table('wyu_beautiful_member_snap_up ms')
            ->field('ms.*,pt.name project_type_name,pt.project_type_id')
            ->leftJoin('wyu_beautiful_project p', 'ms.project_id = p.project_id')
            ->leftJoin('wyu_beautiful_project_type pt', 'p.project_type_id = pt.project_type_id')
            ->where($where)
            ->order($order)
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->select();

        return $this->success(['total' => $total, 'list' => $list]);



        $member_snap_up_model = new MemberSnapUpModel();
        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format', 'status_another'];
        $return = DataLogic::getDataList($member_snap_up_model, $where, $order, $field, $this->request->limit, $this->request->page, $append);
        return $this->success($return);
    }

    public function writeOffSnapupOrder()
    {
        $today = date("Y-m-d", $this->request->time());
        $member_snap_up_id = $this->request->param('member_snap_up_id/d', 0);
        $num = $this->request->param('num/d', 0);
        $remark = $this->request->param('remark');

        if ($num <= 0) return $this->error('核销次数不能小于0');

        if ($member_snap_up_id == 0) return $this->error($this->name . '不存在');
        if (null === $member_snap_up = MemberSnapUpModel::find($member_snap_up_id)) return $this->error($this->name . '不存在');
        if ($member_snap_up->shop_id != $this->request->shopId) return $this->error($this->name . '不存在');
        if ($member_snap_up->status != 1) return $this->error($this->name . '的状态不在待消费');
        if ($member_snap_up->valid_end_time < $today) return $this->error($this->name . '已过期');

        if (null === $member_project = MemberProjectModel::where([
                ['member_id', '=', $member_snap_up->member_id],
                ['source', '=', 'snap_up'],
                ['project_id', '=', $member_snap_up->project_id],
                ['member_snap_up_id', '=', $member_snap_up_id],
                ['total_num', '=', $member_snap_up->total_num],
                ['remain_num', '=', $member_snap_up->remain_num]
            ])->find()) {
            return $this->error($this->name . '不存在');
        }

        if (null === $member = MemberModel::find($member_snap_up->member_id)) return $this->error($this->name . '不存在');
        if ($member->shop_id != $this->request->shopId) return $this->error($this->name . '不存在');

        $remain_num = $member_snap_up->remain_num - $num;
        if ($remain_num < 0) return $this->error($this->name . '的剩余数量不够这次核销');
        Db::startTrans();
        try {
            //处理我的抢购
            $member_snap_up->remain_num = $remain_num;
            if ($remain_num == 0) $member_snap_up->status = 8;
            $member_snap_up->save();
            //处理我的项目
            $member_project->remain_num = $remain_num;
            $member_project->save();

            //添加核销记录
            $res = LogsLogic::project($this->request->shopId, $member->member_id, 'snap_up', $member_snap_up_id, $num, $remain_num, $remark, 1, $this->request->staffId);
            if (!$res) {
                Db::rollback();
                return $this->error('核销失败');
            }

            //打印机
            $printer_logic = new PrinterLogic($this->request->shopId);
            $printer_logic->print('snapUpOrderWriteOff', $res);

            Db::commit();
            return $this->success('核销成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function getMemberSnapUpLogs()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $type = $this->request->param('type/d', 1);
        if (!in_array($type, [1, 2])) $type = 1;
        switch ($type) {
            case 1:
                $return = $this->getWriteOffLogs2($member_id);
                break;
            case 2:
                $return = $this->getApplyLogs2($member_id);
                break;
        }

        return $this->success($return);
    }

    protected function getWriteOffLogs2($member_id)
    {
        $where = [
            ['shop_id', '=', $this->request->shopId],
            ['member_id', '=', $member_id],
            ['source', '=', 'snap_up'],
        ];
        $project_write_off_model = new ProjectWriteOffModel();
        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format'];
        $return = DataLogic::getDataList($project_write_off_model, $where, $order, $field, $this->request->limit, $this->request->page, $append);
        return $return;
    }

    protected function getApplyLogs2($member_id)
    {
        $where = [
            ['shop_id', '=', $this->request->shopId],
            ['member_id', '=', $member_id],
            ['source', '=', 'snap_up'],
        ];
        $apply_logs_model = new ApplyLogsModel();
        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format'];
        $return = DataLogic::getDataList($apply_logs_model, $where, $order, $field, $this->request->limit, $this->request->page, $append);
        return $return;
    }
    /****************************************************** --end--会员详情抢购--end--*********************************************************************/


    /****************************************************** --start--会员详情余额--end--*********************************************************************/

    public function getMemberBalanceLogsList()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $nick_name = $this->request->param('nick_name');
        $mobile = $this->request->param('mobile');
        $operate_time = $this->request->param('operate_time/a');
        $where = [
            ['shop_id', '=', $this->request->shopId]
        ];

        //会员判断
        $member_where = [
            ['shop_id', '=', $this->request->shopId],
            ['is_delete', '=', 0]
        ];
        if (!empty($member_id)) $member_where[] = ['member_id', '=', $member_id];
        if (!empty($nick_name)) $member_where[] = ['nick_name', '=', $nick_name];
        if (!empty($mobile)) $member_where[] = ['mobile', '=', $mobile];
        $member_ids = MemberModel::where($member_where)->column('member_id') ?? [];
        $where[] = ['member_id', 'in', $member_ids];

        //操作时间判断
        if (!empty($operate_time) && count($operate_time) == 2) {
            $operate_bg_time = $operate_time[0];
            $operate_end_time = $operate_time[1];
            if (!empty($operate_bg_time) || !empty($operate_end_time)) {
                if (false !== $operate_bg_time_unix = strtotime($operate_bg_time . " 00:00:00")) {
                    if (false !== $operate_end_time_unix = strtotime($operate_end_time . " 23:59:59")) {
                        $where[] = ['add_time', 'between', [$operate_bg_time_unix, $operate_end_time_unix]];
                    } else {
                        $where[] = ['add_time', '>=', $operate_bg_time_unix];
                    }
                } else {
                    if (false !== $operate_end_time_unix = strtotime($operate_end_time . " 23:59:59")) {
                        $where[] = ['add_time', '<=', $operate_bg_time_unix];
                    }
                }
            }

        }

        $member_balance_logs = new MemberBalanceLogsModel();
        $member_balance_logs = $member_balance_logs->with(['member']);
        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format'];
        $return = DataLogic::getDataList($member_balance_logs, $where, $order, $field, $this->request->limit, $this->request->page, $append);
        return $this->success($return);
    }

    public function getMemberIntegralLogsList()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $nick_name = $this->request->param('nick_name');
        $mobile = $this->request->param('mobile');
        $operate_time = $this->request->param('operate_time/a');
        $where = [
            ['shop_id', '=', $this->request->shopId]
        ];

        //会员判断
        $member_where = [
            ['shop_id', '=', $this->request->shopId],
            ['is_delete', '=', 0]
        ];
        if (!empty($member_id)) $member_where[] = ['member_id', '=', $member_id];
        if (!empty($nick_name)) $member_where[] = ['nick_name', '=', $nick_name];
        if (!empty($mobile)) $member_where[] = ['mobile', '=', $mobile];
        $member_ids = MemberModel::where($member_where)->column('member_id') ?? [];
        $where[] = ['member_id', 'in', $member_ids];

        //操作时间判断
        if (!empty($operate_time) && count($operate_time) == 2) {
            $operate_bg_time = $operate_time[0];
            $operate_end_time = $operate_time[1];
            if (!empty($operate_bg_time) || !empty($operate_end_time)) {
                if (false !== $operate_bg_time_unix = strtotime($operate_bg_time . " 00:00:00")) {
                    if (false !== $operate_end_time_unix = strtotime($operate_end_time . " 23:59:59")) {
                        $where[] = ['add_time', 'between', [$operate_bg_time_unix, $operate_end_time_unix]];
                    } else {
                        $where[] = ['add_time', '>=', $operate_bg_time_unix];
                    }
                } else {
                    if (false !== $operate_end_time_unix = strtotime($operate_end_time . " 23:59:59")) {
                        $where[] = ['add_time', '<=', $operate_bg_time_unix];
                    }
                }
            }

        }

        $member_integral_logs = new MemberIntegralLogsModel();
        $member_integral_logs = $member_integral_logs->with(['member']);
        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format'];
        $return = DataLogic::getDataList($member_integral_logs, $where, $order, $field, $this->request->limit, $this->request->page, $append);
        return $this->success($return);
    }

    public function getMemberBuyLogsList()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $nick_name = $this->request->param('nick_name');
        $mobile = $this->request->param('mobile');
        $operate_time = $this->request->param('operate_time/a');
        $where = [
            ['shop_id', '=', $this->request->shopId],
            ['is_paid', '=', 1]
        ];

        //会员判断
        $member_where = [
            ['shop_id', '=', $this->request->shopId],
        ];
        if (!empty($member_id)) $member_where[] = ['member_id', '=', $member_id];
        if (!empty($nick_name)) $member_where[] = ['nick_name', '=', $nick_name];
        if (!empty($mobile)) $member_where[] = ['mobile', '=', $mobile];
        $member_ids = MemberModel::where($member_where)->column('member_id') ?? [];
        $where[] = ['member_id', 'in', $member_ids];

        //操作时间判断
        if (!empty($operate_time) && count($operate_time) == 2) {
            $operate_bg_time = $operate_time[0];
            $operate_end_time = $operate_time[1];
            if (!empty($operate_bg_time) || !empty($operate_end_time)) {
                if (false !== $operate_bg_time_unix = strtotime($operate_bg_time . " 00:00:00")) {
                    if (false !== $operate_end_time_unix = strtotime($operate_end_time . " 23:59:59")) {
                        $where[] = ['add_time', 'between', [$operate_bg_time_unix, $operate_end_time_unix]];
                    } else {
                        $where[] = ['add_time', '>=', $operate_bg_time_unix];
                    }
                } else {
                    if (false !== $operate_end_time_unix = strtotime($operate_end_time . " 23:59:59")) {
                        $where[] = ['add_time', '<=', $operate_bg_time_unix];
                    }
                }
            }

        }

        $buy_order_model = new BuyOrderModel();
//        $buy_order_model=$buy_order_model->with(['member']);
        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format', 'price', 'discount'];
        $return = DataLogic::getDataList($buy_order_model, $where, $order, $field, $this->request->limit, $this->request->page, $append);
        $list = $return['list'];
        return $this->success($return);
    }

    /****************************************************** --end--会员详情余额--end--*********************************************************************/
}
